#
# opentome_cbr-linux.py
# (c) 2008 Nick Thobe.
#

import os
#from subprocess import *


def rar_file_list( rarfile, comic ):
    """
    Return a list of files in the given rarfile that are supported by OpenTome.
    """
    filenames = []
    unrar_process = os.popen2( "unrar v '%s'" % ( rarfile ) )
    output = unrar_process[1].readlines()
    unrar_process[1].close()
    output = output[output.index( 'Pathname/Comment\n' )+3:-3]
    for filename, attrs in zip( output[::2], output[1::2] ):
	if int( attrs.split()[0] ) > 0 and comic.is_supported_image_format( filename.strip() ):
	    filenames.append( filename.strip() )
    return filenames


def rar_file_open_file( rarfile, filename ):
    """
    Return the extracted contents of filename from rarfile.
    """
    unrar_process = os.popen2( "unrar p -inul '%s' '%s'" % ( rarfile, filename ), 'rb' )
    fdata = unrar_process[1].read()
    unrar_process[1].close()
    # Attempt to fix issues by using subprocess.Popen()
    #unrar_process = Popen( "unrar p -inul '%s' '%s'" % ( rarfile, filename ), shell=True, stdout=PIPE )
    #fdata = unrar_process.stdout.read()
    #unrar_process.wait()
    return fdata


def opentome_cbr_load_all_pages( loader, comic ):
    """
    Load all supported files in the rarfile, comic.path
    """
    files = rar_file_list( comic.path, comic )
    comic.sort_pages( files )
    loader.on_page_count_loaded( comic, len(files) )
    page = 0
    for f in files:
	file = rar_file_open_file( comic.path, f )
        loader.on_page_data_loaded( comic, f, page, file )
        page += 1


def opentome_cbr_load_single_page( loader, comic, page ):
    """
    Load the single page (where page is the page number) from the rarfile, comic.path
    """
    files = rar_file_list( comic.path, comic )
    comic.sort_pages( files )
    loader.on_page_count_loaded( comic, len(files) )
    filename = files[page]
    file = rar_file_open_file( comic.path, filename )
    loader.on_page_data_loaded( comic, filename, page, file )


def opentome_register_plugin():
    return {
        'extensions'       : ['.cbr', '.rar'],
        'load_all_pages'   : opentome_cbr_load_all_pages,
        'load_single_page' : opentome_cbr_load_single_page,
        'pool'             : 1
    }

